<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <el-button type="primary" @click="$router.push('/users/create')">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名、姓名或邮箱"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="info" @click="loadUsers">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
      
      <!-- 用户表格 -->
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="fullName" label="姓名" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phoneNumber" label="电话" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { userApi } from '@/api/userApi'

export default {
  name: 'UserList',
  components: {
    Plus,
    Search,
    Refresh
  },
  setup() {
    const router = useRouter()
    const users = ref([])
    const loading = ref(false)
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const loadUsers = async () => {
      loading.value = true
      try {
        const response = await userApi.getAllUsers()
        if (response.success) {
          users.value = response.data
          total.value = response.data.length
        } else {
          ElMessage.error(response.message || '加载用户列表失败')
        }
      } catch (error) {
        console.error('加载用户列表错误:', error)
        ElMessage.error('加载用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleSearch = async () => {
      if (!searchKeyword.value.trim()) {
        await loadUsers()
        return
      }
      
      loading.value = true
      try {
        const response = await userApi.searchUsers(searchKeyword.value)
        if (response.success) {
          users.value = response.data
          total.value = response.data.length
        } else {
          ElMessage.error(response.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索错误:', error)
        ElMessage.error('搜索失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleEdit = (user) => {
      router.push(`/users/edit/${user.id}`)
    }
    
    const handleDelete = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${user.username}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await userApi.deleteUser(user.id)
        if (response.success) {
          ElMessage.success('删除成功')
          await loadUsers()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除错误:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case 'ACTIVE':
          return 'success'
        case 'INACTIVE':
          return 'warning'
        case 'DELETED':
          return 'danger'
        default:
          return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 'ACTIVE':
          return '活跃'
        case 'INACTIVE':
          return '非活跃'
        case 'DELETED':
          return '已删除'
        default:
          return '未知'
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      return new Date(dateString).toLocaleString('zh-CN')
    }
    
    onMounted(() => {
      loadUsers()
    })
    
    return {
      users,
      loading,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      loadUsers,
      handleSearch,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      getStatusType,
      getStatusText,
      formatDate
    }
  }
}
</script>

<style scoped>
.user-list {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 